/**
 * Created by Will Bean on 2016/4/28.
 */
import React,{Component,PropTypes} from 'react'
import TextInput from './TextInput'
import { Link } from 'react-router'

import style from './addStore.css'
import {myAjax, ROOTURL} from './../publicAPI/publicAPI'

class AdminEditor extends Component {
    constructor() {
        super();

        // 存在密码保护问题
        this.state = {
            username: "",
            password: "",
            pwdAgain: "",
            oldPwd: "",
            delete: false,
            deleteId: -1,
            checkInput: "",
            hasBeenMounted: false  //判断是否已经加载
        };


    }

    componentWillMount(){
        if( this.props.params.id ){
            //根据id获取数据
            var d = {};
            var _this = this;
            var url = ROOTURL + 'user/general/instance.api?id='+ this.props.params.id;
            fetch(url,{
                method: "GET",
                // body : JSON.stringify({}),
                header: 'application/json; charset=utf-8'
            }).then(res=>{
                if(res.ok){
                    console.log(res);
                    res.json().then(data=>{
                        d = {
                            username: data.dname,
                            hasBeenMounted: true
                        };

                        if (!this.state.hasBeenMounted && this.props.params.id)
                            _this.setState(d);
                    })
                }else {
                    console.log('fail')
                }
            })

        }

    }

    handleCreate(){
        if (this.state.username == "") {
            this.setState(
                {checkInput: "请输入用户名"}
            )
        }  else if (this.state.password == "") {
            this.setState(
                {checkInput: "请输入密码"}
            );
        } else if (this.state.password != this.state.pwdAgain) {
            this.setState(
                {checkInput: "两次密码不相同！"}
            )
        } else {
            //save
            this.setState(
                {checkInput: ""}
            )
        
            var url = ROOTURL + 'user/admin/create.api?uname='+this.state.username+'&passwd='+this.state.password;
            fetch(url,{
                method: "POST",
                mode: 'cors',
                header: 'application/json; charset=utf-8'
                // body : JSON.stringify({
                //     // uname : this.state.username,
                //     // passwd : this.state.password
                // })
            }).then(res=>{
                console.log(res)
                if(res.ok || res.status == 204){
                    res.json().then(data=>{
                        console.log(data);
                        alert('保存成功');
                        window.location.href = '/AdministratorM';

                    })
                }else{
                    console.log('fail');
                    alert('保存失败');
                }
            })
        }
    }

    handleSave() {
        const paramsId = this.props.params.id;
        if (this.state.username == "") {
            this.setState(
                {checkInput: "请输入用户名"}
            )
        } else if (paramsId && this.state.oldPwd == "") {
            this.setState(
                {checkInput: "请输入原密码"}
            )
        } else if (this.state.password == "") {
            if (!paramsId)
                this.setState(
                  {checkInput: "请输入密码"}
                );
            else
                this.setState(
                     {checkInput: "请输入新密码"}
                );
        } else if (this.state.password != this.state.pwdAgain) {
            this.setState(
                {checkInput: "两次密码不相同！"}
            )
        } else {
            //save
            this.setState(
                {checkInput: ""}
            )

            var url = ROOTURL + 'user/auth/passwd/passwd.api?login='+this.state.username+'&pass='+this.state.oldPwd+'&newpass='+this.state.password;
            fetch(url,{
                method: "POST",
                // mode: 'no-cors'
                mode: 'cors',
                header: 'application/json; charset=utf-8',
                body: JSON.stringify({
                    //login: this.state.username,
                    // newpass: this.state.password,
                    // pass: this.state.oldPwd
                })
            }).then(res=>{
                if(res.ok || res.status == 204){
                    console.log(res);
                    alert("修改成功");
                    window.location.href = '/AdministratorM';
                }else {
                    alert("修改失败:"+res.msg);
                    // window.location.href = '/AdministratorM';
                }
            })
        }
    }

    doDelete(){
        var _this = this;
        var url = ROOTURL + 'user/general/instance.api?id=' + this.props.params.id;
        fetch(url,{
            method: 'DELETE',
            mode: 'cors',
            // header: {'Access-Control-Allow-Origin': '127.0.0.1',
            //         'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Z-Key',
            //         'Content-Type': 'application/json;charset=utf-8',
            //         'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS'},
            body: JSON.stringify({})
        }).then(function (res) {
            if (res.ok){
                alert('delete success');
                window.location.href = '/AdministratorM'

            }else{
                console.log(res)
            }
        });
        this.setState({
            delete: !this.state.delete
        });
    }

    render() {
        const paramsId = this.props.params.id;
        return (
            <div className="right-wapper">
                <div className="wrap">

                    <div className={style["input_div"]}>
                        <label>用户名</label>
                        {!paramsId ?
                            <TextInput val={this.state.username} inputId="uname" placeHolder="请输入用户名"
                                       onChange={val=>{this.setState({username: val})}}/>
                            :
                            <span id="juname">{this.state.username}</span>}

                    </div>
                    {paramsId ?
                        <div className={style["input_div"]}>
                            <label>原密码</label>
                            <TextInput val={this.state.oldPwd} type="password" inputId="uname" placeHolder="请输入密码"
                                       onChange={val=>{this.setState({oldPwd: val})}}/>
                        </div> : null
                    }

                    <div className={style["input_div"]} id="np">
                        <label>{paramsId ? "新密码" : "密码"}</label>
                        <TextInput val={this.state.password} type="password" inputId="newpass" placeHolder="请输入密码"
                                   onChange={val=>{this.setState({password: val})}}/>
                    </div>
                    <div className={style["input_div"]}>
                        <label>确认密码</label>
                        <TextInput val={this.state.pwdAgain} type="password" inputId="pass" placeHolder="请重新输入密码"
                                   onChange={val=>{this.setState({pwdAgain: val})}}/>
                    </div>
                    { this.state.checkInput != "" ?
                        <span id="hint">{this.state.checkInput}</span> : null
                    }
                    {paramsId ?<button id="submit" className={style["btn_blue"]} onClick={this.handleSave.bind(this)}>保存</button> :
                        <button id="submit" className={style["btn_blue"]} onClick={this.handleCreate.bind(this)}>保存</button>
                    }
                    {paramsId ? <button id="delete" className={style["btn_red"]}
                                        onClick={()=>this.setState({delete: !this.state.delete})}>
                        删除</button> : null}
                    <Link to="/AdministratorM" >
                    <button id="back" className={style["btn_blue"]}>返回</button>
                        </Link>
                </div>

          { this.state.delete ?
                    <div id={style["msgDialog"]}>
                        <div className={style["msgDialog_div"]}><h3 id={style["msgDialog_title"]}>删除提示？</h3><p id={style["msgDialog_content"]}>
                            确认删除？</p>
                            <div className={style["msgDialog_button"]}>
                                <button id={style["msgDialog_yes"]} onClick={this.doDelete.bind(this)}>确定</button>
                                <button id={style["msgDialog_no"]}
                                        onClick={()=>this.setState({delete: !this.state.delete})}>
                                    取消
                                </button>
                            </div>
                        </div>
                    </div> : null}
            </div>
        )
    }
}


export default AdminEditor